//
//  RHAddBuyersCustomersVC.swift
//  IMF
//
//  Created by 黄瑞东 on 2018/9/15.
//  Copyright © 2018年 imf. All rights reserved.
//

import UIKit
import SVProgressHUD

enum pageState:(Int){
    case AddBuyersCustomers = 0
    case ReadBuyersCustomers
    case ModifyBuyersCustomers
}

class RHAddBuyersCustomersVC: RHViewController, UITableViewDelegate, UITableViewDataSource, UIPickerViewDelegate, UIPickerViewDataSource, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    var footerView: UIView?
    var image = UIImage(named: "placeholder")
    var recommendedHousingModel = RHRecommendedHousingModel()
    let array:[String] = [NSLocalizedString("HeadPortraitText", comment: ""),
                          NSLocalizedString("NameText", comment: ""),
                          NSLocalizedString("PhoneText", comment: ""),
                          NSLocalizedString("GenderText", comment: ""),
                          NSLocalizedString("BirthDateText", comment: ""),
                          NSLocalizedString("MaritalText", comment: ""),
                          NSLocalizedString("IncomeText", comment: ""),
                          NSLocalizedString("JobTitleText", comment: ""),
                          NSLocalizedString("JobTypeText", comment: ""),
                          NSLocalizedString("EmailText", comment: ""),
                          NSLocalizedString("WeChatText", comment: ""),
                          NSLocalizedString("QQText", comment: ""),
                          NSLocalizedString("InvestmentObjectiveText", comment: ""),
                          NSLocalizedString("CapitalSourceText", comment: ""),
                          NSLocalizedString("TendencyRoomText", comment: ""),
                          NSLocalizedString("TendencySiteText", comment: ""),
                          NSLocalizedString("TendencyPriceText", comment: ""),
                          NSLocalizedString("TendencySizeText", comment: ""),
                          NSLocalizedString("TendencySchoolText", comment: ""),
                          NSLocalizedString("ProvinceText", comment: ""),
                          NSLocalizedString("CityText", comment: ""),
                          NSLocalizedString("AreaText", comment: ""),
                          NSLocalizedString("AddressText", comment: ""),
                          NSLocalizedString("RemarkText", comment: "")]
    let pickerView = RHPickerView()
    let datePicker = RHDatePicker()
    let GenderArray = ["男", "女"]
    let MaritalArray = ["保密", "已婚", "未婚", "离异"]
    let investmentObjectiveArray = ["长期持有", "自住", "增值投资", "租金收益", "儿女留学居住"]
    let capitalSourceArray = ["国内资金", "海外资金"]
    let tendencyRoomArray = ["独栋别墅", "联排别墅", "公寓"]
    let tendencySiteArray = ["市区", "学校周边", "郊区"]
    let tendencyPriceArray = ["100万人民币以内","100-200万人民币","200-400万人民币","400-700万人民币","700-1000万人民币","1000万以上人民币"]
    let tendencySizeArray = ["100平米以内","150平米以内","200平米以内","250平米以内","300平米以内","400平米以内","500平米以内","500平米以上"]
    let tendencySchoolArray = ["1-5","6-7","8-10"]
    let provinceArray = ["省","省"]
    let cityArray = ["市","市"]
    let areaArray = ["县","县"]
    var pickerViewDataArray = [""]
    var pickerViewDataStorage = Array<Any>()
    var pickerViewIndex = 0
    var submit = UIButton()
    var state:pageState?
    var clientId:Int?
    var tableView: UITableView?
    var buyersDetailsDataRM:RHBuyersDetailsDataResponseModel?
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = state == pageState.AddBuyersCustomers ? NSLocalizedString("AddBuyersCustomersTitle", comment: "") : NSLocalizedString("ViewBuyersCustomersTitle", comment: "")
        loadTableView()
        loadPickerView()
        loadReadClientsApi()
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named: "nav_icon_back"), style: UIBarButtonItemStyle.plain, target: self, action: #selector(cancel))
        self.navigationItem.rightBarButtonItem = state == pageState.ReadBuyersCustomers ? UIBarButtonItem(title: "修改",style: UIBarButtonItemStyle.plain, target: self, action: #selector(modifyData)) : nil
        datePicker.RH_CreateDatePicker(viewController: self)
        self.datePicker.confirmButton.addTarget(self, action: #selector(datePickerConfirmClick), for: .touchUpInside)
        
        if state == pageState.ReadBuyersCustomers{
            SVProgressHUD.show()
            RHAPIManager.sharedInstance.doGetRecommendHouse(clientId: String(clientId!), pageNumber: "1", pageSize: "10", result: {[weak self] (msg, data) in
                guard let weakSelf = self else { return }
                SVProgressHUD.dismiss()
                weakSelf.recommendedHousingModel = (data as? RHRecommendedHousingModel)!
                weakSelf.tableView?.tableFooterView = weakSelf.addFooterView();
                weakSelf.tableView?.reloadData()
            }) { (code, msg) in
                SVProgressHUD.dismiss()
                SVProgressHUD.showInfo(withStatus: msg)
            }
        }
    }
    
    func loadReadClientsApi(){
        if state != pageState.ReadBuyersCustomers {return}
        SVProgressHUD.show()
        RHAPIManager.sharedInstance.doGetClientsDetails(clientId: self.clientId!, result: { [weak self] (msg, data) in
            guard let weakSelf = self else { return }
            SVProgressHUD.dismiss()
            weakSelf.buyersDetailsDataRM =  data as? RHBuyersDetailsDataResponseModel
            weakSelf.pickerViewDataStorage[0] = weakSelf.buyersDetailsDataRM?.photo ?? String()
            weakSelf.pickerViewDataStorage[1] = weakSelf.buyersDetailsDataRM?.name ?? String()
            weakSelf.pickerViewDataStorage[2] = weakSelf.buyersDetailsDataRM?.phone ?? String()
            weakSelf.pickerViewDataStorage[3] = weakSelf.buyersDetailsDataRM?.gender ?? Int() == 0 ? "女" : "男"
            weakSelf.pickerViewDataStorage[4] = weakSelf.buyersDetailsDataRM?.birthdate ?? String()
            weakSelf.pickerViewDataStorage[5] = String(weakSelf.buyersDetailsDataRM?.marital ?? Int())
            weakSelf.pickerViewDataStorage[6] = weakSelf.buyersDetailsDataRM?.income ?? String()
            weakSelf.pickerViewDataStorage[7] = weakSelf.buyersDetailsDataRM?.jobTitle ?? String()
            weakSelf.pickerViewDataStorage[8] = weakSelf.buyersDetailsDataRM?.jobType ?? String()
            weakSelf.pickerViewDataStorage[9] = weakSelf.buyersDetailsDataRM?.email ?? String()
            weakSelf.pickerViewDataStorage[10] = weakSelf.buyersDetailsDataRM?.weixin ?? String()
            weakSelf.pickerViewDataStorage[11] = weakSelf.buyersDetailsDataRM?.qq ?? String()
            weakSelf.pickerViewDataStorage[12] = weakSelf.buyersDetailsDataRM?.investmentObjective ?? String()
            weakSelf.pickerViewDataStorage[13] = weakSelf.buyersDetailsDataRM?.capitalSource ?? String()
            weakSelf.pickerViewDataStorage[14] = weakSelf.buyersDetailsDataRM?.tendencyRoom ?? String()
            weakSelf.pickerViewDataStorage[15] = weakSelf.buyersDetailsDataRM?.tendencySite ?? String()
            weakSelf.pickerViewDataStorage[16] = weakSelf.buyersDetailsDataRM?.tendencyPrice ?? String()
            weakSelf.pickerViewDataStorage[17] = weakSelf.buyersDetailsDataRM?.tendencySize ?? String()
            weakSelf.pickerViewDataStorage[18] = weakSelf.buyersDetailsDataRM?.tendencySchool ?? String()
            weakSelf.pickerViewDataStorage[19] = weakSelf.buyersDetailsDataRM?.province ?? String()
            weakSelf.pickerViewDataStorage[20] = weakSelf.buyersDetailsDataRM?.city ?? String()
            weakSelf.pickerViewDataStorage[21] = weakSelf.buyersDetailsDataRM?.area ?? String()
            weakSelf.pickerViewDataStorage[22] = weakSelf.buyersDetailsDataRM?.address ?? String()
            weakSelf.pickerViewDataStorage[23] = weakSelf.buyersDetailsDataRM?.remark ?? String()
            if weakSelf.pickerViewDataStorage[0] as! String != "" {
                let data = try? Data(contentsOf: URL(string: weakSelf.pickerViewDataStorage[0] as! String)!)
                if data != nil{
                    weakSelf.image = UIImage(data: data!)
                }
            }
            weakSelf.tableView?.reloadData()
        }) { (code, msg) in
            SVProgressHUD.dismiss()
            SVProgressHUD.showInfo(withStatus: msg)
        }
    }
    
    func loadPickerView(){
        pickerViewDataStorage = Array<String>(repeating: "", count: array.count)
        pickerView.RH_CreatePickerView(viewController: self)
        pickerView.confirmButton.addTarget(self, action: #selector(ConfirmClick), for: .touchUpInside)
    }
    
    func loadDictsApi(dictsId: Int){
        SVProgressHUD.show()
        RHAPIManager.sharedInstance.doDicts(id: dictsId, result: {(msg, model) in
            SVProgressHUD.dismiss()
        }) { (code, msg) in
           SVProgressHUD.dismiss()
           SVProgressHUD.showInfo(withStatus: msg)
        }
    }
    
    @objc func cancel() {
        if state == pageState.AddBuyersCustomers {
            self.dismiss(animated: false, completion: nil)
        }else{
            self.navigationController?.popViewController(animated: true)
        }
    }
    
    @objc func modifyData() {
        if state == pageState.ModifyBuyersCustomers {return}
        self.navigationItem.rightBarButtonItem = nil
        self.title = NSLocalizedString("ModifyBuyersCustomersTitle", comment: "")
        self.state = pageState.ModifyBuyersCustomers
        self.tableView?.tableFooterView = addFooterView();
        self.tableView?.reloadData()
    }
    
    @objc func datePickerConfirmClick() {
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy年MM月dd日"
        pickerViewDataStorage[4] = formatter.string(from: self.datePicker.datePicker.date)
        self.datePicker.hideView()
        self.tableView?.reloadData()
    }
    
    func loadTableView(){
        self.tableView = RHTableView(frame: CGRect.zero, style: .plain)
        self.tableView?.delegate = self;
        self.tableView?.dataSource = self;
        self.tableView?.register(RHKeyValueTableViewCell.self, forCellReuseIdentifier: "RHKeyValueTableViewCell")
        self.tableView?.register(RHTextFieldTableCell.self, forCellReuseIdentifier: "RHTextFieldTableCell")
        self.tableView?.register(RHHeadPortraitTableViewCell.self, forCellReuseIdentifier: "RHHeadPortraitTableViewCell")
        self.tableView?.tableFooterView = addFooterView();
        self.view.addSubview(self.tableView!)
        
        self.tableView?.snp.makeConstraints { [weak self](make) in
            guard let weakSelf = self else { return }
            make.top.equalTo(10)
            make.left.equalTo(weakSelf.view.snp.left)
            make.right.equalTo(weakSelf.view.snp.right)
            if #available(iOS 11.0, *) {
                make.bottom.equalTo(weakSelf.view.snp.bottom)
            } else {
                make.bottom.equalTo(weakSelf.view.snp.bottom)
            }
        }
        
        NotificationCenter.default
            .addObserver(self,selector: #selector(keyboardWillShow(_:)),
                         name: NSNotification.Name.UIKeyboardWillShow, object: nil)
        //监听键盘隐藏通知
        NotificationCenter.default
            .addObserver(self,selector: #selector(keyboardWillHide(_:)),
                         name: NSNotification.Name.UIKeyboardWillHide, object: nil)
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return array.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.row == 0{
            let cell: RHHeadPortraitTableViewCell = tableView.dequeueReusableCell(withIdentifier: "RHHeadPortraitTableViewCell", for: indexPath) as! RHHeadPortraitTableViewCell
            cell.headPortraitImageView?.image = image
            cell.accessoryType = state == pageState.ReadBuyersCustomers ? UITableViewCell.AccessoryType.none : UITableViewCell.AccessoryType.disclosureIndicator
            return cell
        } else if indexPath.row == 3 || indexPath.row == 4 || indexPath.row == 5 ||
            indexPath.row == 12 || indexPath.row == 13 || indexPath.row == 14 ||
            indexPath.row == 15 || indexPath.row == 16 || indexPath.row == 17 ||
            indexPath.row == 18 || indexPath.row == 19 || indexPath.row == 20 ||
            indexPath.row == 21 {
            let cell: RHKeyValueTableViewCell = tableView.dequeueReusableCell(withIdentifier: "RHKeyValueTableViewCell", for: indexPath) as! RHKeyValueTableViewCell
            cell.leftLabel?.text = array[indexPath.row]
            cell.rightLabel?.text = "-"
            cell.rightLabel?.textColor = RHAppSkinColor.sharedInstance.secondaryTextColor
            if pickerViewDataStorage[indexPath.row] as! String != "" {
                cell.rightLabel?.textColor = RHAppSkinColor.sharedInstance.emphasisTextColor
                cell.rightLabel?.text = pickerViewDataStorage[indexPath.row] as? String
            }
            
            cell.accessoryType = state == pageState.ReadBuyersCustomers ? UITableViewCell.AccessoryType.none : UITableViewCell.AccessoryType.disclosureIndicator
            return cell
        } else{
            let cell: RHTextFieldTableCell = tableView.dequeueReusableCell(withIdentifier: "RHTextFieldTableCell", for: indexPath) as! RHTextFieldTableCell
            cell.leftLabel?.text = array[indexPath.row]
            cell.rightTextField?.delegate = self
            cell.rightTextField?.tag = indexPath.row
            cell.rightTextField?.text = ""
            cell.rightTextField?.isUserInteractionEnabled = (state == pageState.ReadBuyersCustomers ? false : true)

            if pickerViewDataStorage[indexPath.row] as! String != "" {
                cell.rightTextField?.text = pickerViewDataStorage[indexPath.row] as? String
            }
            
            cell.rightTextField?.placeholder = "-"
            return cell
        }
    }
    
    func addFooterView() -> UIView? {
        let footerView = UIView(frame: CGRect(x: 0, y: 0, width: (self.tableView?.frame.width)!, height: 75.0))
        let buttonName = self.recommendedHousingModel.data != nil ? NSLocalizedString("RecommendedHousing", comment: "") : "暂⽆无分享房源"
        submit = UIButton.xz_commonButtonWithTitle(title: self.state == pageState.ReadBuyersCustomers ? buttonName: NSLocalizedString("SubmitText", comment: ""), isEnabled: false)
        footerView.addSubview(submit)
        submit.addTarget(self, action: #selector(submitButtonClick), for: .touchUpInside)
        submit.isEnabled = self.state == pageState.ReadBuyersCustomers ? true : false
        if self.state == pageState.ReadBuyersCustomers && self.recommendedHousingModel.data == nil{
            submit.isEnabled = false
        }
        submit.snp.makeConstraints({(make) in
            make.top.equalTo(15.0)
            make.left.equalTo(20.0)
            make.right.equalTo(-20.0)
            make.height.equalTo(44)
        })
        return footerView
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return indexPath.row == 0 ? 100 : 44
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if state == pageState.ReadBuyersCustomers { return }
        self.view.endEditing(true)
        
        if indexPath.row == 0{
            RHAlertController().RH_LoadAlertController(viewController: self)
        }else if indexPath.row == 3 || indexPath.row == 5 ||
            indexPath.row == 12 || indexPath.row == 13 || indexPath.row == 14 ||
            indexPath.row == 15 || indexPath.row == 16 || indexPath.row == 17 ||
            indexPath.row == 18 || indexPath.row == 19 || indexPath.row == 20 ||
            indexPath.row == 21 {
            pickerView.showView()
        }
        switch indexPath.row {
        case 3:
            reloadPickerViewData(data: GenderArray as NSArray, index: indexPath.row)
            break
        case 4:
            self.datePicker.showView()
            break
        case 5:
            reloadPickerViewData(data: MaritalArray as NSArray, index: indexPath.row)
            break
        case 12:
            reloadPickerViewData(data: investmentObjectiveArray as NSArray, index: indexPath.row)
            break
        case 13:
            reloadPickerViewData(data: capitalSourceArray as NSArray, index: indexPath.row)
            break
        case 14:
            reloadPickerViewData(data: tendencyRoomArray as NSArray, index: indexPath.row)
            break
        case 15:
            reloadPickerViewData(data: tendencySiteArray as NSArray, index: indexPath.row)
            break
        case 16:
            reloadPickerViewData(data: tendencyPriceArray as NSArray, index: indexPath.row)
            break
        case 17:
            reloadPickerViewData(data: tendencySizeArray as NSArray, index: indexPath.row)
            break
        case 18:
            reloadPickerViewData(data: tendencySchoolArray as NSArray, index: indexPath.row)
            break
        case 19:
            reloadPickerViewData(data: provinceArray as NSArray, index: indexPath.row)
            break
        case 20:
            reloadPickerViewData(data: cityArray as NSArray, index: indexPath.row)
            break
        case 21:
            reloadPickerViewData(data: areaArray as NSArray, index: indexPath.row)
            break
        default: break
        }
    }
    
    func reloadPickerViewData(data: NSArray, index: Int) {
        pickerViewIndex = index
        pickerViewDataArray = data as! [String]
        pickerView.pickerView.reloadAllComponents()
        pickerView.pickerView.selectRow(0, inComponent: 0, animated: true)
        pickerView.showView()
    }
    
    @objc func submitButtonClick() {
        SVProgressHUD.show()
        if state == pageState.AddBuyersCustomers {
            RHAPIManager.sharedInstance.doAddClients(arrayData: pickerViewDataStorage, result: { (msg, model) in
                SVProgressHUD.dismiss()
                self.dismiss(animated: true, completion: nil)
            }) { (code, msg) in
                SVProgressHUD.dismiss()
                SVProgressHUD.showInfo(withStatus: msg)
            }
        }else if state == pageState.ModifyBuyersCustomers{
            RHAPIManager.sharedInstance.doPutClients(arrayData: pickerViewDataStorage, clientId: (self.buyersDetailsDataRM?.clientId!)!, result: { (msg, data) in
                SVProgressHUD.dismiss()
                self.dismiss(animated: true, completion: nil)
            }) { (code, msg) in
                SVProgressHUD.dismiss()
                SVProgressHUD.showInfo(withStatus: msg)
            }
        }else {
            SVProgressHUD.dismiss()
            let recommendedHousingVC = RHRecommendedHousingVC()
            recommendedHousingVC.clientId = self.buyersDetailsDataRM?.clientId
            self.navigationController?.pushViewController(recommendedHousingVC, animated: true)
        }
        
    }
    
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }
    
    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return pickerViewDataArray.count
    }
    
    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String?{
        return String(pickerViewDataArray[row])
    }
    
    @objc func ConfirmClick() {
        pickerViewDataStorage[pickerViewIndex] = pickerViewDataArray[pickerView.pickerView.selectedRow(inComponent: 0)]
        dataValueChanged()
        pickerView.hideView()
        self.tableView?.reloadData()
    }
    
    func dataValueChanged() {
        var isEnabledButton = true
        
        for item in self.pickerViewDataStorage{
            if item as! String == ""{
                isEnabledButton = false
            }
        }
        submit.isEnabled = isEnabledButton
    }
    
    func imagePickerController(_ picker: UIImagePickerController,
                               didFinishPickingMediaWithInfo info: [String : Any]) {
        SVProgressHUD.show()
        picker.dismiss(animated: true, completion: {
            () -> Void in
            let pickedImage:UIImage = info[UIImagePickerControllerOriginalImage] as! UIImage
            RHAPIManager.sharedInstance.doClientsPhoto(image: pickedImage, fileName: "头像", result: { [weak self] (msg, data) in
                guard let weakSelf = self else { return }
                SVProgressHUD.dismiss()
                let model = data as! RHHeadPortraitResoponseModel
                weakSelf.pickerViewDataStorage[0] = model.data ?? String()
                weakSelf.dataValueChanged()
                weakSelf.tableView?.reloadData()
            }) { (code, msg) in
                SVProgressHUD.dismiss()
                SVProgressHUD.showInfo(withStatus: msg)
            }
        })
    }
}

extension RHAddBuyersCustomersVC: UITextFieldDelegate {
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        guard let text = textField.text else {
            return true
        }
        
        let textLength = text.count + string.count - range.length
        
        if textField.tag == 2 {
            let scanner = Scanner(string: string)
            let numbers = NSCharacterSet(charactersIn: "0123456789")
            if !scanner.scanCharacters(from: numbers as CharacterSet, into: nil) && string.count != 0 {
                return false
            }
            return textLength <= 11
        }else {
            return textLength <= 30
        }
    }
    
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        view.endEditing(true)
        return true
    }
    
    func textFieldDidEndEditing(_ textField: UITextField) {
        pickerViewDataStorage[textField.tag] = textField.text ?? String()
        dataValueChanged()
    }
    
    @objc func keyboardWillShow(_ notification: Notification) {
        self.pickerView.hideView()
        self.datePicker.hideView()
        
        let userInfo = (notification as NSNotification).userInfo!
        //键盘尺寸
        let keyboardSize = (userInfo[UIKeyboardFrameBeginUserInfoKey]
            as! NSValue).cgRectValue
        var contentInsets:UIEdgeInsets
        //判断是横屏还是竖屏
        let statusBarOrientation = UIApplication.shared.statusBarOrientation
        if UIInterfaceOrientationIsPortrait(statusBarOrientation) {
            contentInsets = UIEdgeInsetsMake(64.0, 0.0, (keyboardSize.height), 0.0);
        } else {
            contentInsets = UIEdgeInsetsMake(64.0, 0.0, (keyboardSize.width), 0.0);
        }
        //tableview的contentview的底部大小
        self.tableView!.contentInset = contentInsets;
        self.tableView!.scrollIndicatorInsets = contentInsets;
    }
    
    // 键盘隐藏
    @objc func keyboardWillHide(_ notification: Notification) {
        //还原tableview的contentview大小
        let contentInsets:UIEdgeInsets = UIEdgeInsetsMake(0, 0.0, 0, 0.0);
        self.tableView!.contentInset = contentInsets
        self.tableView!.scrollIndicatorInsets = contentInsets
    }
}
